import io

from minio import Minio
from minio.error import S3Error
from PIL import Image
from utils.logger import logger


class MinioConfig:
    def __init__(
        self,
        endpoint="localhost:9000",
        access_key="minioadmin",
        secret_key="minioadmin",
        bucket_name="test-bucket",
        secure=False,
    ):
        self.endpoint = endpoint
        self.access_key = access_key
        self.secret_key = secret_key
        self.secure = secure
        self.client = Minio(
            self.endpoint,
            access_key=self.access_key,
            secret_key=self.secret_key,
            secure=self.secure,
        )
        self.bucket_name = bucket_name
        # 检查存储桶是否存在
        if not self.client.bucket_exists(self.bucket_name):
            try:
                # 若不存在则创建存储桶
                self.client.make_bucket(self.bucket_name)
            except S3Error as e:
                logger.error(f"创建存储桶 {self.bucket_name} 失败: {e}")

    def set_bucket_name(self, bucket_name):
        self.bucket_name = bucket_name

    def get_image(self, image_name) -> Image:
        try:
            # 从 MinIO 获取对象（文件）
            response = self.client.get_object(self.bucket_name, image_name)

            # 将响应流读取到内存中的字节流
            image_data = io.BytesIO()
            for chunk in response.stream(1024 * 1024):  # 每次读取 1MB
                image_data.write(chunk)
            image_data.seek(0)  # 将指针移回开头

            # 使用 Pillow 打开图片
            image = Image.open(image_data)
            logger.info(f"成功读取图片，格式：{image.format}, 大小：{image.size}")

            # 关闭响应流
            response.close()
            response.release_conn()

            return image
        except S3Error as e:
            logger.error(f"MinIO 错误: {e}")
            return None
        except Exception as e:
            logger.error(f"其他错误: {e}")
            return None

    def get_image_url(self, image_name) -> str:
        url = self.client.presigned_get_object(self.bucket_name, image_name)
        return url
